<template>
  <div class="page-container">
    <h2>房东管理</h2>
    <el-table :data="landlords" style="width: 100%" stripe>
      <el-table-column prop="account" label="账号"></el-table-column>
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号码"></el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            @click="toggleStatus(scope.$index, scope.row)"
            :type="scope.row.status === 1 ? 'warning' : 'primary'"
          >
            {{ scope.row.status === 1 ? "禁用" : "启用" }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="resetPassword(scope.$index, scope.row)"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import userApi from "@/api/modules/user";
import api from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";

const landlords = ref([]);

async function fetchLandlords() {
  try {
    const response = await userApi.byRole("ROLE_Landlord");
    landlords.value = response.data;
  } catch (error) {
    console.error("Failed to fetch landlords:", error);
  }
}

onMounted(() => {
  fetchLandlords();
});
async function toggleStatus(index, row) {
  try {
    const newStatus = row.status === 1 ? 2 : 1;

    // 添加请求确认对话框
    await ElMessageBox.confirm(
      `确定要${newStatus === 1 ? "启用" : "禁用"}该用户吗？`,
      "操作确认",
      { type: "warning" }
    );

    // 调用接口时传递完整参数对象
    await api.user.toggleUserStatus(row.id, newStatus);

    // 更新本地数据并重新获取最新数据
    const { data } = await userApi.byRole("ROLE_Landlord");
    landlords.value = data;

    ElMessage.success(`已${newStatus === 1 ? "启用" : "禁用"}用户`);
  } catch (error) {
    if (error !== "cancel") {
      console.error("状态更新失败:", error);
      ElMessage.error(error.response?.data?.message || "操作失败");
    }
  }
}

async function resetPassword(index, row) {
  try {
    await api.user.resetUserPassword(row.id);
    ElMessage.success("密码已重置为123456");
  } catch (error) {
    console.error("密码重置失败:", error);
    ElMessage.error(error.response?.data?.message || "操作失败");
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.el-table th {
  background-color: #f5f7fa;
}
.el-table__row {
  height: 48px;
}
.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}
</style>
